import 'package:common_utils/common_utils.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';
import 'package:pinput/pinput.dart';
import 'package:xr_base/colors.dart';
import 'package:xr_base/dimens.dart';
import 'package:xr_base/enums.dart';
import 'package:xr_base/func_utils.dart';
import 'package:xr_base/image_constants.dart';
import 'package:xr_base/styles.dart';
import 'package:xr_base/view_util.dart';
import 'package:xr_dio/xr_dio.dart';

import '../provider/login_provider.dart';
import '../router/navigator_util.dart';
import '../router/unit_router.dart';
import '../widgets/common_w_h_button.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({Key? key}) : super(key: key);

  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  @override
  Widget build(BuildContext context) {
    return KeyboardDismissOnTap(
      child: Scaffold(
          resizeToAvoidBottomInset: false,
          body: Stack(
            children: [
              localImage(ImageConstants.login_img_bg,
                  width: screenWidth(context), height: screenHeight(context), fit: BoxFit.cover),
              SingleChildScrollView(
                child: const LoginWidget(),
              )
            ],
          )),
    );
  }
}

class LoginWidget extends StatefulWidget {
  const LoginWidget({Key? key}) : super(key: key);

  @override
  _LoginWidgetState createState() => _LoginWidgetState();
}

class _LoginWidgetState extends State<LoginWidget> {
  TextEditingController _phoneController = TextEditingController.fromValue(TextEditingValue(
      text: '', selection: TextSelection.fromPosition(TextPosition(affinity: TextAffinity.downstream, offset: 0))));

  TextEditingController _authCodeController = TextEditingController.fromValue(TextEditingValue(
      text: '', selection: TextSelection.fromPosition(TextPosition(affinity: TextAffinity.downstream, offset: 0))));

  final _pinputFocusNode = FocusNode();

  final Color _borderColor = Color.fromRGBO(30, 60, 87, 1);

  bool _isCheckd = false;

  /// 定时器
  TimerUtil? _mCountDownTimerUtil;

  String? _mCountDownTick;

  VerificationStatus _verificationStatus = VerificationStatus.normal;

  final int _mTotalTime = 60 * 1000;

  CancelToken? _cancelToken;

  @override
  initState() {
    /// 定时器
    _initAuthCodeTimerUtil();
    _cancelToken = CancelToken();
  }

  _initAuthCodeTimerUtil() {
    _mCountDownTimerUtil = TimerUtil(mTotalTime: _mTotalTime);
    _mCountDownTimerUtil?.setOnTimerTickCallback((int tick) {
      int _tick = tick ~/ 1000;
      if (_tick.toInt() == 0) {
        _mCountDownTimerUtil?.setTotalTime(_mTotalTime);
        setState(() {
          _mCountDownTick = null;
          if (_verificationStatus == VerificationStatus.waitting) {
            _verificationStatus = VerificationStatus.normal;
          }
        });
      } else {
        setState(() {
          _mCountDownTick = _tick.toString();
          if (_verificationStatus == VerificationStatus.normal) {
            _verificationStatus = VerificationStatus.waitting;
          }
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: Dimens.dn_16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Gaps.getVGap(Dimens.dn_50),
          InkWell(
            onTap: () {
              Navigator.pop(context);
            },
            child: Padding(
              padding: EdgeInsets.only(top: Dimens.dn_10, right: Dimens.dn_10, bottom: Dimens.dn_10),
              child: localImage(ImageConstants.login_guanbi, width: Dimens.dn_15, height: Dimens.dn_15),
            ),
          ),
          Gaps.getVGap(Dimens.dn_60),
          _outsideBox(Text(
            '登录注册',
            style: TextStyles.ts_30_w900_000000,
            overflow: TextOverflow.ellipsis,
          )),
          Gaps.getVGap(Dimens.dn_40),
          _outsideBox(Text(
            '手机号码',
            style: TextStyles.ts_18_w500_010101,
            overflow: TextOverflow.ellipsis,
          )),
          Gaps.getVGap(Dimens.dn_20),
          _outsideBox(Row(
            children: [
              Expanded(
                child: TextField(
                    controller: _phoneController,
                    keyboardType: TextInputType.number,
                    style: TextStyles.ts_24_W5OO_010101,
                    inputFormatters: <TextInputFormatter>[
                      LengthLimitingTextInputFormatter(11),
                    ],
                    decoration: Decorations.ts_18_w500_black_160163166_spacing('请输入手机号码'),
                    obscureText: false,
                    onChanged: (String? value) {
                      setState(() {});
                    }),
              ),
              Gaps.getHGap(Dimens.dn_10),
              InkWell(
                onTap: (_verificationStatus == VerificationStatus.normal)
                    ? () {
                        if (_phoneController.text.trim().isEmpty) {
                          showToast('请输入手机号码');
                          return;
                        }

                        if (!RegexUtil.isMobileExact(_phoneController.text.trim())) {
                          showToast('手机号码格式不正确');
                          return;
                        }
                        _pinputFocusNode.unfocus();
                        LoginProvider.getSmsCode(phone: _phoneController.text.trim(), occasionType: '1');
                        _mCountDownTimerUtil?.startCountDown();
                      }.throttleWithTimeout(timeout: 1000)
                    : null,
                child: Container(
                  padding: EdgeInsets.symmetric(vertical: Dimens.dn_10),
                  width: Dimens.dn_96,
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                    border: (_verificationStatus == VerificationStatus.normal)
                        ? null
                        : Border.all(color: Colours.black_000000.withOpacity(0.3), width: 0.5),
                    borderRadius: BorderRadius.circular(Dimens.dn_18),
                    gradient: (_verificationStatus == VerificationStatus.normal)
                        ? LinearGradient(
                            colors: [Colours.blue_236AF6, Colours.blue_4DB4FF],
                            begin: Alignment.centerLeft,
                            end: Alignment.centerRight)
                        : null,
                  ),
                  child: Text(
                    _authCodeTitle,
                    style: (_verificationStatus == VerificationStatus.normal)
                        ? TextStyles.ts_15_w500_FFFFFF
                        : TextStyles.ts_15_w500_000000_042,
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
              ),
              Gaps.getHGap(Dimens.dn_24),
            ],
          )),
          Gaps.getVGap(Dimens.dn_20),
          _outsideBox(Text(
            '验证码',
            style: TextStyles.ts_18_w500_010101,
            overflow: TextOverflow.ellipsis,
          )),
          Gaps.getVGap(Dimens.dn_10),
          _outsideBox(Pinput(
            length: 6,
            pinAnimationType: PinAnimationType.slide,
            defaultPinTheme: defaultPinTheme,
            showCursor: true,
            cursor: cursor,
            preFilledWidget: preFilledWidget,
            controller: _authCodeController,
            focusNode: _pinputFocusNode,
            onChanged: (String code) {
              setState(() {});
            },
            onCompleted: (String code) {
              setState(() {});
            },
          )),
          Gaps.getVGap(Dimens.dn_50),
          _outsideBox(
            CommonMaginButton(
              '登 录',
              borderRadius: Dimens.dn_25,
              color: _allowNext ? null : Colours.black_000000.withOpacity(0.3),
              child: Text("登 录", style: TextStyles.ts_20_w900_FFFFFF),
              padding: EdgeInsets.only(top: Dimens.dn_15, bottom: Dimens.dn_15),
              gradient: _allowNext
                  ? LinearGradient(
                      colors: [Colours.blue_236AF6, Colours.blue_4DB4FF],
                      begin: Alignment.centerLeft,
                      end: Alignment.centerRight)
                  : null,
              timeout: 2000,
              onTap: _allowNext
                  ? () async {
                      FocusScope.of(context).unfocus(); //取消焦点

                      if (!RegexUtil.isMobileExact(_phoneController.text.trim())) {
                        showToast('手机号码格式不正确');
                        return;
                      }

                      if (!_isCheckd) {
                        showToast('请先同意隐私政策和用户服务协议');
                        return;
                      }

                      LoginProvider.login(
                          phone: _phoneController.text.trim(),
                          smsCode: _authCodeController.text.trim(),
                          cancelToken: _cancelToken,
                          occasionType: '1',
                          onOk: (String result) {
                            NavigatorUtil.pushPage(context, UnitRouter.set_user_info).then((value) {
                              debugPrint('---😆😆补全资料,value:$value😆😆---');
                              if (ObjectUtil.isNotEmpty(value)) {}
                            });
                            // Navigator.pop(context, result);
                          });
                    }
                  : () {
                      NavigatorUtil.pushPage(context, UnitRouter.set_user_info).then((value) {
                        debugPrint('---😆😆补全资料,value:$value😆😆---');
                        if (ObjectUtil.isNotEmpty(value)) {}
                      });
                    },
            ),
          ),
          Gaps.getVGap(Dimens.dn_13),
          _outsideBox(Center(
            child: Text(
              '未注册的用户将自动注册',
              style: TextStyles.ts_12_w500_black_160163166,
              overflow: TextOverflow.ellipsis,
            ),
          )),
          Gaps.getVGap(Dimens.dn_30),
          _pirvatePolicy(),
          Gaps.getVGap(Dimens.dn_15),
          _outsideBox(Center(
            child: InkWell(
              onTap: () {},
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  localImage(ImageConstants.login_kefu_4, width: Dimens.dn_27, height: Dimens.dn_27),
                  Gaps.getHGap(Dimens.dn_2),
                  Text(
                    '联系客服',
                    style: TextStyles.ts_13_w500_black_160163166,
                    overflow: TextOverflow.ellipsis,
                  ),
                ],
              ),
            ),
          )),
        ],
      ),
    );
  }

  _outsideBox(Widget child) {
    return Padding(
      padding: EdgeInsets.only(left: Dimens.dn_24, right: Dimens.dn_24),
      child: child,
    );
  }

  get defaultPinTheme => PinTheme(
        width: 56,
        height: 56,
        textStyle: TextStyle(
          fontSize: Dimens.dn_24,
          fontWeight: FontWeight.w500,
          color: Colours.black_010101,
        ),
        decoration: const BoxDecoration(),
      );

  get cursor => Column(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          Container(
            width: 56,
            height: 3,
            decoration: BoxDecoration(
              color: _borderColor,
              borderRadius: BorderRadius.circular(8),
            ),
          ),
        ],
      );

  get preFilledWidget => Column(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          Container(
            width: 56,
            height: 3,
            decoration: BoxDecoration(
              color: Colours.gray_D6D6D6D6,
              borderRadius: BorderRadius.circular(8),
            ),
          ),
        ],
      );

  _pirvatePolicy() {
    return Center(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          InkWell(
            onTap: () {
              setState(() {
                _isCheckd = !_isCheckd;
              });
            },
            child: Padding(
              padding: EdgeInsets.only(left: Dimens.dn_23, right: 2),
              child: localImage(_isCheckd ? ImageConstants.ico_queding_b : ImageConstants.ico_weigouxuan,
                  width: 17.0, height: 17.0),
            ),
          ),
          Expanded(
            child: RichText(
              text: TextSpan(text: '我已阅读并同意', style: TextStyles.ts_13_w500_black_160163166, children: <TextSpan>[
                TextSpan(
                    text: '《用户服务协议》',
                    style: TextStyles.ts_13_w500_010101,
                    recognizer: TapGestureRecognizer()
                      ..onTap = () {
                        // HiNavigator.getInstance().onJumpTo(RouteStatus.agreementPage,
                        //     args: {Strings.login_register_policy_type: Strings.login_user_protocol});
                      }),
                TextSpan(
                  text: '和',
                  style: TextStyles.ts_13_w500_black_160163166,
                ),
                TextSpan(
                    text: '《隐私政策》',
                    style: TextStyles.ts_13_w500_010101,
                    recognizer: TapGestureRecognizer()
                      ..onTap = () {
                        // HiNavigator.getInstance().onJumpTo(RouteStatus.agreementPage,
                        //     args: {Strings.login_register_policy_type: Strings.login_private_policy});
                      })
              ]),
            ),
          )
        ],
      ),
    );
  }

  get _authCodeTitle {
    if (_verificationStatus == VerificationStatus.normal) {
      return '获取验证码';
    }
    return '已发送$_mCountDownTick' + 's';
  }

  bool get _allowNext {
    return (_phoneController.text.trim().isNotEmpty &&
            (_phoneController.text.trim().length == 11) &&
            _authCodeController.text.trim().isNotEmpty) &&
        (_authCodeController.text.trim().length == 6);
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _authCodeController.dispose();

    _pinputFocusNode.dispose();
    _mCountDownTimerUtil?.cancel();

    _cancelToken?.cancel('login task is canceled');
    debugPrint('---😆😆登录dispose😆😆---');
  }
}
